#include "airvisibleudp.h"

AirVisibleUdp::AirVisibleUdp(QObject *parent) : UdpBase(parent)
{

}

void AirVisibleUdp::startProcess()
{
    m_runStatus = true;
}

void AirVisibleUdp::stopProcess()
{
    m_runStatus = false;
}

void AirVisibleUdp::setTargetFps(int fps)
{

}

void AirVisibleUdp::onInitUdp()
{
    m_udpReceive = new QUdpSocket(this);

    QNetworkInterface netInterface = getNetInterface(m_bindIP);

    //windows上必须绑定AnyIPv4不然就会绑定失败,linux可以绑定具体的组播ip
    bool isOK = m_udpReceive->bind(QHostAddress::AnyIPv4, m_bindPort, QUdpSocket::ShareAddress);

    if(isOK == false){
        qDebug()<<QString("组播bind失败%1 %2").arg(m_bindIP).arg(m_bindPort);
        return;
    }

    isOK = m_udpReceive->joinMulticastGroup(QHostAddress(m_bindIP), netInterface);
    if(isOK == false){
        qDebug()<<QString("组播jion失败%1").arg(m_bindIP);
        return;
    }

    qDebug() << "组播成功:" << m_bindIP << ":" << m_bindPort;
    connect(m_udpReceive, &QUdpSocket::readyRead, this, &AirVisibleUdp::onReceive);
}

void AirVisibleUdp::onReceive()
{
    while (m_udpReceive->hasPendingDatagrams()) {

        //如果状态设置是停止，即false
        if(!m_runStatus) {
            continue;
        }

        QNetworkDatagram datagram = m_udpReceive->receiveDatagram();

        //如果是广播方式，在多网卡情况下，需要获取当前绑定网卡的index，来和收到的网卡的index对比，如果
        //不一致则舍弃，避免重复接收
         if(datagram.interfaceIndex() != static_cast<uint>(m_netCardIndex)) {
             continue;
         }

        QString srcIp = datagram.senderAddress().toString().section(":", -1);
        //quint16 srcPort = static_cast<quint16>(datagram.senderPort());

        if(srcIp != m_srcIP || datagram.data().size() <= 8) {
            continue;
        }
        emit sigToSend(datagram.data());    //直接转发到发送端
    }
}
